package main_com.Controlers.friend;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import main_com.mapper.FriendMapper;
import main_com.pojo.LoginBean;
import main_com.pojo.LookFriendBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;

/**
 * @author Administrator
 */
@Controller
@RequestMapping("/LookFriendController")
public class LookFriendController {

    @Autowired
    FriendMapper friendMapper;

    @RequestMapping("/lookFriend")
    protected void lookFriend(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userName = "";
            HttpSession session = request.getSession();
            ArrayList login = (ArrayList) session.getAttribute("login");

            if (login == null || login.size() == 0) {
                response.sendRedirect("http://localhost/login.jsp");
                return;
            } else {
                for (int i = login.size() - 1; i >= 0; i--) {
                    LoginBean nn = (LoginBean) login.get(i);
                    userName = nn.getUserName();
                }
            }

            // 获取当前页数，默认是第1页
            String pageParam = request.getParameter("page");
            int currentPage = (pageParam != null) ? Integer.parseInt(pageParam) : 1;
            int pageSize = 3; // 每页显示3条数据
            int offset = (currentPage - 1) * pageSize;

            // 获取总记录数
            int totalCount = friendMapper.getTotalFriendCount(userName);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            // 获取当前页的联系人数据
            ArrayList<LookFriendBean> friendslist = friendMapper.getFriendByUserNameWithPagination(userName, offset, pageSize);

            // 将数据和分页信息存入 session
            session.setAttribute("friendslist", friendslist);
            session.setAttribute("currentPage", currentPage);
            session.setAttribute("totalPages", totalPages);

            response.sendRedirect("http://localhost/friendManager/lookFriend.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}